package cn.matezk.lianlian.service.impl;

import cn.matezk.lianlian.service.IOSSService;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OSSService implements IOSSService {
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucket}")
    private String bucket;

    @Override
    public String upload(String folder, InputStream inputStream, String suffix) {
        String path = folder.concat("/").concat(UUID.randomUUID().toString().replace("-", "")).concat(".").concat(suffix);
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(new PutObjectRequest(bucket, path, inputStream));
        return "http://".concat(bucket).concat(".").concat(endpoint).concat("/").concat(path);
    }

    @Override
    public String uploadCustom(String folder, InputStream inputStream, String fname) {
        String path = folder.concat("/").concat(fname);
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(new PutObjectRequest(bucket, path, inputStream));
            return "http://".concat(bucket).concat(".").concat(endpoint).concat("/").concat(path);
        } finally {
            ossClient.shutdown();
        }
    }

    @Override
    public void delete(String path) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        path = path.replace("http://", "");
        ossClient.deleteObject(bucket, path.substring(path.indexOf("/") + 1));
    }
}
